<template>
  <CommonPage>
    <div class="h-full flex flex-items-center">
      <div class="timeList h-full w200 flex flex-col pr18">
        <div class="title mb12">任务周期</div>
        <n-scrollbar class="timeContent flex-1">
          <div
            v-for="(item, index) in data.cycleList"
            :key="index"
            class="time"
            :class="{ active: data.activeCycleId == item.id }"
            @click="data.activeCycleId = item.id"
          >
            {{ item.echoCycle }}
          </div>
        </n-scrollbar>
      </div>
      <div class="line"></div>
      <div class="tableContainer h-full flex flex-col flex-1 flex-items-end pl24">
        <MyTabs v-model="active" :options="tabs" class="mb12" />
        <div class="time mb12 w-full">{{ activeCycleName }}</div>
        <n-data-table
          :columns="columns"
          :data="data.list"
          :bordered="true"
          :single-line="false"
          :loading="data.loading"
          :max-height="`calc( 100vh - ${isSelf ? 360 : 310}px )`"
          :row-key="(row) => row['id']"
        />

        <n-flex class="mt16">
          <n-button
            v-if="isSelf"
            v-permission="`task_day_my_add`"
            ghost
            type="primary"
            size="small"
            @click="methods.addTask"
          >
            <i class="i-material-symbols:add mr-4 text-18" />
            添加
          </n-button>
        </n-flex>
      </div>
    </div>
    <n-modal
      v-model:show="data.showFlag"
      preset="card"
      transform-origin="center"
      :style="{ width: '900px' }"
      title="添加日常任务"
    >
      <n-form
        ref="$form"
        :model="model"
        label-placement="left"
        label-align="right"
        :label-width="100"
        :style="{ padding: '0 20px' }"
        require-mark-placement="left"
      >
        <n-form-item
          label="组别"
          path="deptId"
          :rule="[{ required: true, message: '请选择组别!' }]"
        >
          <AsyncSelect
            v-model:value="model.deptId"
            label-key="name"
            value-key="dept_id"
            :options="() => taskProjectApi.deptAllList().then((res) => res.data)"
            :disabled="isSelf"
          />
        </n-form-item>
        <n-form-item
          label="姓名"
          path="userId"
          :rule="[{ required: true, message: '请选择姓名!' }]"
        >
          <AsyncSelect
            v-model:value="model.userId"
            :options="methods.getUserOptions"
            label-key="name"
            value-key="userId"
            :remote="true"
            :init-remote="true"
            :disabled="!model.deptId || isSelf"
          />
        </n-form-item>
        <n-form-item
          label="项目名称"
          path="projectId"
          :rule="[{ required: true, message: '请选择项目!' }]"
        >
          <AsyncSelect
            v-model:value="model.projectId"
            :options="methods.getProjectOptions"
            :remote="true"
            :init-remote="true"
            :disabled="!model.deptId || !model.userId"
          />
        </n-form-item>
        <n-flex>
          <n-form-item label="周度计划" path="isCompleted">
            <n-checkbox
              v-model:checked="model.isCompleted"
              :checked-value="1"
              :unchecked-value="0"
              :disabled="!isSelf || !model.deptId || !model.userId || !model.projectId"
            />
          </n-form-item>
          <n-form-item path="weeklyWork" class="flex-1">
            <n-input
              v-model:value="model.weeklyWork"
              :class="{ isCompleted: model.isCompleted === 1 ? true : false }"
              clearable
              :maxlength="300"
              :disabled="!isSelf || !model.deptId || !model.userId || !model.projectId"
              show-count
              type="textarea"
              :autosize="{ minRows: 1 }"
            />
          </n-form-item>
        </n-flex>
        <n-form-item label="备注" path="remark">
          <n-input
            v-model:value="model.remark"
            clearable
            :maxlength="300"
            :disabled="!isSelf || !model.deptId || !model.userId || !model.projectId"
            show-count
            type="textarea"
            :autosize="{ minRows: 1 }"
          />
        </n-form-item>
        <n-form-item label="完成日期" path="completeTime">
          <n-date-picker
            v-model:formatted-value="model.completeTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :time-picker-props="{ format: 'HH:mm' }"
            placeholder="选择时间"
            clearable
            :disabled="!isSelf || !model.deptId || !model.userId || !model.projectId"
          />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-flex justify="center">
          <n-button @click="data.showFlag = false">取消</n-button>
          <n-button color="#0A56D8FF" :loading="data.submitFlag" @click="methods.onValidate">
            确定
          </n-button>
        </n-flex>
      </template>
    </n-modal>
  </CommonPage>
</template>

<script setup lang="jsx">
import { usePermissionStore } from '@/store'
import { useAuthTabs } from '@/hooks/useAuthTabs'
import { Delete } from '@vicons/carbon'
import { debounce } from 'lodash-es'
import * as taskDailyApi from '@/api/taskDaily'
import * as projectApi from '@/api/project'
import * as taskProjectApi from '@/api/taskProject'
import { userSel } from '@/api/user'
import { useUserStore } from '@/store'
defineOptions({ name: 'DailyIndex' })
const userStore = useUserStore()
const { hasPermission } = usePermissionStore()
const { tabs, active } = useAuthTabs([
  { label: '本人', value: 'self', key: 'task_day_my' },
  { label: '本组', value: 'dept', key: 'task_day_dept' },
  { label: '全部', value: 'all', key: 'task_day_all' },
])
const columns = [
  {
    title: '组别',
    key: 'deptName',
    width: 80,
    rowSpan: (row) => data.list.filter((item) => item.deptId === row.deptId).length || 1,
  },
  {
    title: '姓名',
    key: 'userName',
    width: 80,
    rowSpan: (row) =>
      data.list.filter((item) => item.deptId === row.deptId && item.userId === row.userId).length ||
      1,
  },
  {
    title: '项目名称',
    key: 'projectName',
    width: 120,
    rowSpan: (row) =>
      data.list.filter(
        (item) =>
          item.deptId === row.deptId &&
          item.userId === row.userId &&
          item.projectId === row.projectId
      ).length || 1,
    render: (row) =>
      `${row.projectName} V.${row.projectVersion || 0}.${row.projectVersionMinor || 0}`,
  },
  {
    title: '周度计划',
    key: 'plan',
    width: 200,
    render: ({ deptId, userId, projectId, isCompleted, weeklyWork, id }, index) => (
      <div class="flex gap-8">
        <div class="flex-col gap-8">
          <n-checkbox
            checked={isCompleted}
            onUpdateChecked={(val) => methods.handleChange(index, 'isCompleted', val)}
            checked-value={1}
            unchecked-value={0}
            disabled={
              !isSelf.value ||
              !deptId ||
              !userId ||
              !projectId ||
              !hasPermission('task_day_my_update')
            }
          />
          <n-tooltip trigger="hover">
            {{
              trigger: () => (
                <n-icon
                  v-permission="task_day_my_delete"
                  v-show={isSelf.value}
                  component={Delete}
                  size={16}
                  class="cursor-pointer"
                  onClick={() => methods.removeTask(index, id)}
                ></n-icon>
              ),
              default: () => '删除此次周度计划',
            }}
          </n-tooltip>
        </div>
        <n-input
          class={isCompleted ? 'isCompleted' : ''}
          value={weeklyWork}
          onUpdateValue={(val) => methods.handleChange(index, 'weeklyWork', val)}
          clearable
          maxlength={300}
          disabled={
            !isSelf.value ||
            !deptId ||
            !userId ||
            !projectId ||
            !hasPermission('task_day_my_update')
          }
          type="textarea"
          autosize={{
            minRows: 1,
          }}
        />
      </div>
    ),
  },
  {
    title: '备注',
    key: 'remark',
    width: 200,
    render: ({ deptId, userId, projectId, remark }, index) => (
      <n-input
        value={remark}
        onUpdateValue={(val) => methods.handleChange(index, 'remark', val)}
        clearable
        maxlength={300}
        disabled={
          !isSelf.value || !deptId || !userId || !projectId || !hasPermission('task_day_my_update')
        }
        type="textarea"
        autosize={{
          minRows: 1,
        }}
      />
    ),
  },
  {
    title: '完成日期',
    key: 'completeTime',
    width: 160,
    render: ({ deptId, userId, projectId, completeTime }, index) => (
      <n-date-picker
        formatted-value={completeTime}
        onUpdateFormattedValue={(val) => methods.handleChange(index, 'completeTime', val)}
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm"
        time-picker-props={{ format: 'HH:mm' }}
        placeholder="选择时间"
        clearable
        disabled={
          !isSelf.value || !deptId || !userId || !projectId || !hasPermission('task_day_my_update')
        }
      />
    ),
  },
]

const data = reactive({
  cycleList: [],
  activeCycleId: null,
  activeCycleName: null,
  loading: false,
  list: [],
  showFlag: false,
  submitFlag: false,
})
const isSelf = computed(() => active.value === 'self')
const $form = ref(null)
const model = ref()
const activeCycleName = computed(
  () => data.cycleList.find((item) => data.activeCycleId === item.id)?.echoCycle || ''
)
const methods = reactive({
  getUserOptions(name, userId) {
    return userSel({ name, userId }).then((res) => res.data)
  },
  getProjectOptions(searchVal, id) {
    return projectApi.listAll({ searchVal, id }).then((res) =>
      res.data.map((item) => ({
        label: `${item.projectName} V.${item.projectVersion || 0}.${item.projectVersionMinor || 0}`,
        value: item.id,
      }))
    )
  },
  taskMold() {
    return {
      id: null,
      deptId: isSelf.value ? userStore.deptId : null,
      userId: isSelf.value ? userStore.userId : null,
      projectId: null,
      isCompleted: 0,
      weeklyWork: null,
      remark: null,
      completeTime: null,
    }
  },
  addTask() {
    // data.list.push(methods.taskMold())
    model.value = methods.taskMold()
    data.showFlag = true
  },
  removeTask(index, id) {
    data.list.splice(index, 1)
    if (id) {
      taskDailyApi.del({ id })
    }
  },
  async getCycleList() {
    const res = await taskDailyApi.cycleList()
    data.cycleList = res.data
    if (res?.data?.length) {
      const { id } = res.data[0]
      data.activeCycleId = id
    }
  },
  async getTask(projectTaskCalendarId, type) {
    data.loading = true
    const map = {
      self: taskDailyApi.selfList,
      dept: taskDailyApi.deptList,
      all: taskDailyApi.allList,
    }
    const res = await map[type]({ projectTaskCalendarId })
    data.list = res.data
    data.loading = false
  },
  handleChange(index, key, value) {
    data.list[index][key] = value
    methods.handleSave(index)
  },
  handleSave: debounce((index) => {
    const info = data.list[index]
    if (info.id) {
      taskDailyApi.edit(info)
    } else {
      taskDailyApi.add({ ...info, projectTaskCalendarId: data.activeCycleId }).then((res) => {
        data.list[index].id = res.data.id
      })
    }
  }, 500),
  onValidate(e) {
    e.preventDefault()
    $form.value.validate((errors) => {
      if (!errors) {
        data.submitFlag = true
        taskDailyApi
          .add({ ...model.value, projectTaskCalendarId: data.activeCycleId })
          .then(() => {
            $message.success('添加日常任务成功！')
            methods.getTask(data.activeCycleId, active.value)
            data.showFlag = false
          })
          .finally(() => {
            data.submitFlag = false
          })
      }
    })
  },
})
onBeforeMount(() => {
  methods.getCycleList()
})
watchEffect(() => {
  if (data.activeCycleId && active.value) {
    methods.getTask(data.activeCycleId, active.value)
  }
})
</script>

<style scoped lang="scss">
.timeList {
  .title {
    font-weight: 400;
    font-size: 16px;
    color: #030912;
    line-height: 24px;
    text-align: left;
    font-style: normal;
  }
  .timeContent {
    overflow-y: auto;
    .time {
      font-family: Helvetica;
      font-size: 14px;
      color: #686f7c;
      line-height: 22px;
      text-align: left;
      font-style: normal;
      cursor: pointer;
      margin-bottom: 12px;
      &:last-of-type {
        margin-bottom: 0;
      }
      &.active {
        font-family: Helvetica, Helvetica;
        font-weight: bold;
        font-size: 14px;
        color: #0a56d8;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }
    }
  }
}
.line {
  width: 1px;
  height: 100%;
  background: #e7eaf0;
}
.tableContainer {
  overflow: hidden;
  .time {
    font-family: ArialMT;
    font-size: 16px;
    color: #030912;
    line-height: 24px;
    text-align: left;
    font-style: normal;
  }
}

// 行背景
:deep(.n-data-table .n-data-table-thead, ) {
  background-color: transparent !important;
}
:deep(.n-data-table .n-data-table-th, .n-data-table .n-data-table-table) {
  background-color: transparent !important;
}
:deep(.n-data-table) {
  --n-merged-th-color-hover: transparent;
  --n-merged-td-color-hover: transparent;
  // --n-merged-td-color-hover: RGBA(218, 230, 249, 1);
}
:deep(.isCompleted .n-input__textarea-el) {
  text-decoration: line-through;
}
</style>
